package io.netty.example.http.websocketx.mynio;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.example.echo.EchoServerHandler;

import java.net.InetSocketAddress;

/**
 * 编写NIO Netty程序
 * 服务端代码
 *
 * @author sunzhuang
 * @date 2022年03月20日 1:14 PM
 */

public class EchoServer {

    /** 服务器启动的端口号 */
    private final int port;

    public EchoServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) throws InterruptedException {
        //从启动参数中获取端口号
        if (args.length != 1) {
            System.err.println("Usage " + EchoServer.class.getSimpleName() + "<post>:" + args + "");
        }
        int port = Integer.parseInt(args[0]);

        //启动服务
        new EchoServer(port).start();
    }

    /** 启动 NIO 服务 */
    private void start() throws InterruptedException {
        //netty的应用程序中负责引导服务器和客户端
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        EventLoopGroup group = new NioEventLoopGroup();
        final ChannelHandler echoServerHandler = new EchoServerHandler();
        try {
            serverBootstrap.group(group)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(port))
                    //处理一个 IO 事件或拦截一个 IO 操作，并将其转发给它的下一个处理程序
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        /** 初始化pipeline channel 并添加监听器 */
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(echoServerHandler);
                        }
                    });

            //启动服务器
            ChannelFuture future = serverBootstrap.bind().sync();
            System.out.println(EchoServer.class.getSimpleName() + "服务启动，port:" + port);
            future.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }

    }
}
